package com.stu.web.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.locale.converters.DateLocaleConverter;

import com.stu.domain.Customer;
import com.stu.service.CustomerService;
import com.stu.service.impl.CustomerServiceImpl;
import com.stu.utils.FormBeanUtil;
import com.stu.web.formbean.CustomFormBean;

public class AddCustom extends HttpServlet {
	private CustomerService s=new CustomerServiceImpl();
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		CustomFormBean formbean=FormBeanUtil.fillFormBean(CustomFormBean.class, request);
		if (!formbean.validate()) {
			request.setAttribute("formbean", formbean);
			request.getRequestDispatcher("/addCustom.jsp").forward(request, response);
			return;
		}
		Customer c=new Customer();
		ConvertUtils.register(new DateLocaleConverter(), Date.class);
		try {
			BeanUtils.copyProperties(c, formbean);
		} catch (Exception e) {
			request.setAttribute("message", "服务器忙");
			request.getRequestDispatcher("/message.jsp").forward(request, response);
		}
		
		if (formbean.getHobby()!=null&&formbean.getHobby().length>0) {
			StringBuffer sb=new StringBuffer();
			for (int i = 0; i < formbean.getHobby().length; i++) {
				if (i>0) {
					sb.append(",");
				}
				sb.append(formbean.getHobby()[i]);
			}
			c.setHobby(sb.toString());
		}
		s.addCustomer(c);
		request.setAttribute("message", "添加成功");
		request.getRequestDispatcher("/message.jsp").forward(request, response);
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
